package dbs

import (
	"ManageServer/conf"
	"ManageServer/utils/encryption"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"io/ioutil"
)

var db *gorm.DB

//初始化数据库
func CreateDB() (err error) {
	engine, _ := conf.ConfFile.GetValue("sql", "engine")
	if engine == "mysql" {
		rootUsername, _ := conf.ConfFile.GetValue("mysqlRoot", "username")
		rootDatabase, _ := conf.ConfFile.GetValue("mysqlRoot", "database")
		rootPassword, _ := conf.ConfFile.GetValue("mysqlRoot", "password")
		rootHost, _ := conf.ConfFile.GetValue("mysqlRoot", "host")
		rootPort, _ := conf.ConfFile.GetValue("mysqlRoot", "port")

		username, _ := conf.ConfFile.GetValue("mysql", "username")
		database, _ := conf.ConfFile.GetValue("mysql", "database")
		password, _ := conf.ConfFile.GetValue("mysql", "password")
		charset, _ := conf.ConfFile.GetValue("mysql", "charset")

		// 管理员 打开 mysql 数据库
		db, err = gorm.Open("mysql", rootUsername+":"+rootPassword+"@tcp("+rootHost+":"+rootPort+")/"+rootDatabase)
		if err != nil {
			return
		}
		// 8.0 创建新数据库用户
		err = db.Exec("CREATE USER if not exists '" + username + "'@'%' IDENTIFIED BY'" + password + "';").Error
		if err != nil {
			return err
		}

		// 创建数据库
		err = db.Exec("create database if not exists " + database + " charset " + charset + ";").Error
		defer func() {
			if err != nil {
				db.Exec("drop database " + database + ";")
			}
		}()
		if err != nil {
			return err
		}
		// 数据库授权
		err = db.Exec("grant all privileges on " + database + ".* to '" + username + "'@'%';").Error
		if err != nil {
			return err
		}
		// 刷新权限
		err = db.Exec("flush privileges;").Error
		if err != nil {
			return err
		}
		// 登入数据库
		err = db.Exec("use " + database + ";").Error
		if err != nil {
			return err
		}
	}
	if engine == "sqlite" {
		path, err := conf.ConfFile.GetValue("sqlite", "path")
		if err != nil {
			return err
		}

		db, err = gorm.Open("sqlite3", path)
	}

	err = CreateTable(db)
	return
}

func CreateTable(db *gorm.DB) (err error) {
	autoIncrementOffset, _ := conf.ConfFile.GetValue("mysqlConfig", "autoIncrementOffset")
	err = db.Exec("SET global auto_increment_offset =" + autoIncrementOffset + ";").Error
	if err != nil {
		return err
	}

	autoIncrementIncrement, _ := conf.ConfFile.GetValue("mysqlConfig", "autoIncrementIncrement")
	err = db.Exec("SET global auto_increment_increment =" + autoIncrementIncrement + ";").Error
	if err != nil {
		return err
	}
	if !db.HasTable(&DbSession{}) {
		err = db.CreateTable(&DbSession{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbUser{}) {
		err = db.CreateTable(&DbUser{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbDepartment{}) {
		err = db.CreateTable(&DbDepartment{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbPlatformToken{}) {
		err = db.CreateTable(&DbPlatformToken{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbOperation{}) {
		err = db.CreateTable(&DbOperation{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbLog{}) {
		err = db.CreateTable(&DbLog{}).Error
		if err != nil {
			return
		}
	}

	if !db.HasTable(&DbFile{}) {
		err = db.CreateTable(&DbFile{}).Error
		if err != nil {
			return
		}
	}
	if !db.HasTable(&DbAccompanyRecord{}) {
		err = db.CreateTable(&DbAccompanyRecord{}).Error
		if err != nil {
			return
		}
	}
	if !db.HasTable(&DbStaffRecord{}) {
		err = db.CreateTable(&DbStaffRecord{}).Error
		if err != nil {
			return
		}
	}
	if !db.HasTable(&DbEquipmentDispatch{}) {
		err = db.CreateTable(&DbEquipmentDispatch{}).Error
		if err != nil {
			return
		}
	}
	if !db.HasTable(&DbConfig{}) {
		err = db.CreateTable(&DbConfig{}).Error
		if err != nil {
			return
		}
	}
	if !db.HasTable(&Patient{}) {
		err = db.CreateTable(&Patient{}).Error
		if err != nil {
			return
		}
	}
	//if !db.HasTable(&DbInpatientDic{}) {
	//	err = db.CreateTable(&DbInpatientDic{}).Error
	//	if err != nil {
	//		return
	//	}
	//}

	rootDatabase, _ := conf.ConfFile.GetValue("mysql", "database")
	// 数据库授权
	autoIncrement, _ := conf.ConfFile.GetValue("mysqlConfig", "autoIncrement")
	err = db.Exec("ALTER TABLE `" + rootDatabase + "`.`db_staff_records` AUTO_INCREMENT = " + autoIncrement + ";").Error
	if err != nil {
		return err
	}
	err = db.Exec("ALTER TABLE `" + rootDatabase + "`.`db_accompany_records` AUTO_INCREMENT = " + autoIncrement + ";").Error
	if err != nil {
		return err
	}

	//设置max_allowed_packet
	err = db.Exec("set global max_allowed_packet = 100 * 1024 * 1024;").Error
	if err != nil {
		return err
	}
	//初始化性别头像
	male, err := ioutil.ReadFile(conf.DirPath + "/files/image/male.png")
	if err != nil {
		return
	}
	var file = DbFile{
		Hash:  encryption.Hash(male),
		Name:  "male.png",
		Value: male,
	}
	err = db.Create(&file).Error
	if err != nil {
		return
	}

	female, err := ioutil.ReadFile(conf.DirPath + "/files/image/female.png")
	if err != nil {
		return
	}
	file = DbFile{
		Hash:  encryption.Hash(female),
		Name:  "female.png",
		Value: female,
	}
	err = db.Create(&file).Error
	if err != nil {
		return
	}

	defaultFace, err := ioutil.ReadFile(conf.DirPath + "/files/image/default.png")
	if err != nil {
		return
	}
	file = DbFile{
		Hash:  encryption.Hash(defaultFace),
		Name:  "default.png",
		Value: defaultFace,
	}
	err = db.Create(&file).Error
	if err != nil {
		return
	}

	var meetingroom_devices = []string{"白板", "空调", "会议桌椅", "沙发", "讲台", "麦克风", "大屏电视", "投影仪", "摄像设备"}
	var meetingroom_device_imgs = []string{}
	// 初始化设备图标
	for _, device := range meetingroom_devices {
		dv, err1 := ioutil.ReadFile(conf.DirPath + "/files/image/" + device + ".png")
		if err1 != nil {
			return err1
		}
		hash := encryption.Hash(dv)
		file = DbFile{
			Hash:  hash,
			Name:  device + ".png",
			Value: dv,
		}
		err1 = db.Create(&file).Error
		if err1 != nil {
			return err1
		}
		meetingroom_device_imgs = append(meetingroom_device_imgs, hash)
	}

	// 后台角色 超级管理员、管理员、职工
	password := encryption.CryptoMd5("ZHYQ2022", "")
	var user = DbUser{
		Name:           "超级管理员",
		Phone:          "18888888888",
		Role:           "超级管理员",
		Status:         "启用中",
		Gender:         "男",
		Department:     "超级管理",
		EditedPassword: true,
		Vip:            1,
		Password:       password,
		Identity:       "职工",
	}

	var user1 = DbUser{
		Name:           "刘德华",
		Phone:          "17986576733",
		Role:           "患陪",
		Status:         "启用中",
		Gender:         "男",
		Department:     "内科",
		EditedPassword: true,
		Password:       password,
		Identity:       "患陪",
	}

	var user3 = DbUser{
		Name:           "黎明",
		Phone:          "17986576723",
		Role:           "管理员",
		Status:         "启用中",
		Gender:         "男",
		Department:     "内科",
		EditedPassword: true,
		Password:       password,
		Identity:       "职工",
	}

	var user2 = DbUser{
		Name:           "郭富城",
		Phone:          "18956342876",
		Role:           "职工",
		Status:         "启用中",
		Gender:         "男",
		Department:     "外科",
		EditedPassword: true,
		Password:       password,
		Identity:       "职工",
	}

	user.Password = password
	err = db.Create(&user).Error
	if err != nil {
		return
	}

	user.Password = password
	err = db.Create(&user1).Error
	if err != nil {
		return
	}

	user.Password = password
	err = db.Create(&user2).Error
	if err != nil {
		return
	}

	user.Password = password
	err = db.Create(&user3).Error
	if err != nil {
		return
	}

	var departments = []string{"消化内科", "血液内科", "呼吸与危重症医学科", "心血管内科", "感染病科",
		"内分泌科", "神经内科", "精神卫生科", "皮肤性病科", "肾脏内科", "风湿免疫科", "康复医学科", "老年病科",
		"放疗科", "国际医疗部", "门诊部", "高血压科", "全科医学科", "普通外科", "骨科", "耳鼻咽喉-头颈外科", "眼科",
		"口腔科", "心胸外科", "神经外科", "泌尿外科", "整形美容烧伤外科", "肿瘤科", "日间手术中心", "肝胆胰外科", "胃肠外科",
		"甲状腺外科", "乳腺科", "血管外科", "疝与腹壁外科", "口腔内科", "口腔修复科", "口腔正畸科", "口腔颌面外科", "口腔门诊综合护理单元",
		"妇科", "遗传实验室", "妇科二", "产科", "生殖中心", "优生遗传室", "妇产科门诊", "超声能量诊断", "儿科", "小儿外科", "中医科", "急诊医学中心",
		"门诊输液室", "重症医学科", "核医学科", "麻醉科", "疼痛科", "病理科", "影像科", "普通放射影像科", "超声影像科", "核磁影像科", "CT影像科",
		"肿瘤与血管介入科", "门急诊医学检验科", "住院部医学检验科", "医学检验科", "输血科", "手术室", "药学部", "中药配方颗粒药房",
		"调剂科", "门诊西药房", "门诊儿科药房", "急诊药房", "住院药房", "中药房", "草药房", "药品采供科", "制剂科", "普通制剂室", "静配中心",
		"临床药学科", "妇科二中药房", "供应室", "医学装备管理处", "病案统计室", "营养科", "医学工程技术管理科", "远程会诊中心", "党委办公室",
		"院长办公室", "纪检办公室", "监察室", "工会", "团委", "人事处", "人才建设办公室", "信息管理科", "审计处", "宣传部", "图书信息科", "编辑部",
		"组织统战部", "计划财务处", "派出机构管理科", "计划生育办公室", "多学科联合诊疗（MDT）中心", "口腔多学科诊疗中心", "医务处", "健康管理中心",
		"护理部", "感染管理科", "医保办", "新型农村合作医疗管理办公室", "老干部科", "防保科", "医院协会文化委", "院史办", "保卫科", "公费医疗科",
		"质控部", "运营部", "医疗辅助服务部", "住院部", "后勤保障处", "科技处", "临床药物研究机构", "内基实验室", "外科总论试验室", "科研实验室",
		"护校", "教务处", "教学部", "研究生处", "学生处", "医师规范化培训基地", "临床技能实训中心", "第三方部门"}
	for _, v := range departments {
		var departments1 = DbDepartment{Department: v}
		err = db.Create(&departments1).Error
		if err != nil {
			fmt.Println("初始化部门失败 ：", v)
			continue
		}
	}

	//添加基础配置表
	config1 := DbConfig{
		Key:       "hospital_name",
		Name:      "医院名称",
		Value:     "山西医科大学第一医院",
		FormType:  "input",
		CreatedBy: "超级管理员",
	}
	config2 := DbConfig{
		Key:       "approval_pass_period_staff",
		Name:      "职工审批有效期",
		Value:     "30",
		FormType:  "input",
		CreatedBy: "超级管理员",
	}

	config3 := DbConfig{
		Key:       "approval_pass_period_third_staff",
		Name:      "第三方职工审批有效期",
		Value:     "30",
		FormType:  "input",
		CreatedBy: "超级管理员",
	}

	config4 := DbConfig{
		Key:       "approval_pass_period_accompany",
		Name:      "患陪审批有效期",
		Value:     "30",
		FormType:  "input",
		CreatedBy: "超级管理员",
	}

	config5 := DbConfig{
		Key:          "photo_issued_machine",
		Name:         "下发任务",
		Value:        "1",
		FormType:     "switch",
		ValueExplain: "1开 0关",
		CreatedBy:    "超级管理员",
	}
	err = db.Create(&config1).Error
	if err != nil {
		return
	}
	err = db.Create(&config2).Error
	if err != nil {
		return
	}
	err = db.Create(&config3).Error
	if err != nil {
		return
	}
	err = db.Create(&config4).Error
	if err != nil {
		return
	}
	err = db.Create(&config5).Error
	if err != nil {
		return
	}
	return
}

//增加sql语句
func ImplementSql() (err error) {

	engine, _ := conf.ConfFile.GetValue("sql", "engine")
	if engine == "mysql" {
		rootUsername, _ := conf.ConfFile.GetValue("mysqlRoot", "username")
		rootDatabase, _ := conf.ConfFile.GetValue("mysqlRoot", "database")
		rootPassword, _ := conf.ConfFile.GetValue("mysqlRoot", "password")
		rootHost, _ := conf.ConfFile.GetValue("mysqlRoot", "host")
		rootPort, _ := conf.ConfFile.GetValue("mysqlRoot", "port")

		username, _ := conf.ConfFile.GetValue("mysql", "username")
		database, _ := conf.ConfFile.GetValue("mysql", "database")
		password, _ := conf.ConfFile.GetValue("mysql", "password")

		// 管理员 打开 mysql 数据库
		db, err = gorm.Open("mysql", rootUsername+":"+rootPassword+"@tcp("+rootHost+":"+rootPort+")/"+rootDatabase)
		if err != nil {
			return
		}

		// 8.0 创建新数据库用户
		err = db.Exec("CREATE USER if not exists '" + username + "'@'%' IDENTIFIED BY'" + password + "';").Error
		if err != nil {
			return err
		}

		// 数据库授权
		err = db.Exec("grant all privileges on " + database + ".* to '" + username + "'@'%';").Error
		if err != nil {
			return err
		}
		// 刷新权限
		err = db.Exec("flush privileges;").Error
		if err != nil {
			return err
		}
		// 登入数据库
		err = db.Exec("use " + database + ";").Error
		if err != nil {
			return err
		}
		// 数据库授权
		err = db.Exec("INSERT INTO `epmanage`.`db_departments` ( `department`, `level`, `created_at`, `updated_at`) VALUES ( '扫黑办', '2', '2022-03-30 03:20:46', '2022-03-30 03:20:46');").Error
		if err != nil {
			return err
		}
	}
	return nil
}
